﻿using CreateAuthorizeCode.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CreateAuthorizeCode
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HttpClient _httpClient;
        private  string POST_URL = "http://localhost:5300/api/v1/ceremony/user/authorizecode";
        private  string GET_URL = "http://localhost:5300/api/v1/ceremony/user/authorizecodes";
        private string CreatePrize_Url = "http://localhost:5300/api/v1/bobing/prize";
        string[] prizeNameArray = new[] { "一秀", "二举", "四进", "三红", "对堂", "状元（四红）", "状元（五子）", "状元（五红）", "状元（六勃黑）", "状元（遍地锦）", "状元（六勃红）", "状元（插金花）" };
        public MainWindow()
        {
            InitializeComponent();
            this.tbPostUrl.Text = POST_URL;
            this.tbGetUrl.Text = GET_URL;
            this.tbCreatePrizeUrl.Text = CreatePrize_Url;
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
                _httpClient.Timeout = new TimeSpan(0,0,30);
            }
        }
        /// <summary>
        /// 生成授权码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            int num = 0;
            if (string.IsNullOrEmpty(this.tbNum.Text))
            {
                MessageBox.Show("请输入生成授权码数量");
            }
            else if (int.TryParse(this.tbNum.Text.Trim(),out num))
            {
                try
                {
                    AuthorizeCode code = new AuthorizeCode();
                    code.Password = "0599024";
                    code.Num = num;
                    string json = JsonConvert.SerializeObject(code);
                    StringContent content = new StringContent(json);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var response = await _httpClient.PostAsync(POST_URL, content);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        MessageBox.Show("生成授权码成功");
                    }
                    else
                    {
                        MessageBox.Show("授权码生成失败");
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show("授权码生成失败:" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("请输入数量");
            }
        }

        private async void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var response = await _httpClient.GetAsync(GET_URL);
                if(response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    this.tbCodes.Clear();
                    string message = await response.Content.ReadAsStringAsync();
                    List<Authorize> authorizes = JsonConvert.DeserializeObject<List<Authorize>>(message);
                    foreach(var item in authorizes)
                    {
                       await this.tbCodes.Dispatcher.BeginInvoke(new Action(() => {
                           this.tbCodes.AppendText(item.Code + "，");
                       }));
                    }
                    MessageBox.Show("查询完成");
                }
                else
                {
                    MessageBox.Show("获取授权码失败");
                }
                
            }
            catch(Exception ex)
            {
                MessageBox.Show("获取授权码失败:" + ex.Message);
            }
        }
        /// <summary>
        /// 提交接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInterface_Click(object sender, RoutedEventArgs e)
        {
            PasswordWindow pw = new PasswordWindow();
            pw.Closed += (s, e) =>
            {
                if (pw.IsPasswordOK)
                {
                    POST_URL = this.tbPostUrl.Text.Trim();
                    GET_URL = this.tbGetUrl.Text.Trim();
                    CreatePrize_Url = this.tbCreatePrizeUrl.Text.Trim();
                    MessageBox.Show("设置成功");
                }
            };
            pw.Show();
        }
        //提交
        private async void btnPrizeJF_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int prizeType = this.cbPrizeType.SelectedIndex + 1;
                if(prizeType < 0)
                {
                    MessageBox.Show("选择奖项类型");
                    return;
                }

                int integral;
                if (!int.TryParse(this.tbIntegral.Text,out integral))
                {
                    MessageBox.Show("积分格式错误");
                    return;
                }
                string prizeName = prizeNameArray[this.cbPrizeType.SelectedIndex];
                BobingPrize bobingPrize = new BobingPrize(prizeType, prizeName, integral);
                string json = JsonConvert.SerializeObject(bobingPrize);
                StringContent content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var response = await _httpClient.PostAsync(CreatePrize_Url, content);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    MessageBox.Show("生成奖项成功");
                }
                else
                {
                    MessageBox.Show("生成奖项失败");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
